/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年1月27日         Root.Lu
 */

package com.tianci.appstore.controller.manager;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.RemoteException;

import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.Cache;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.AppData;
import com.coocaa.x.service.litecontent.data.apps.com_coocaa_app.RP_Installed_Apps;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.tianci.appstore.controller.AppStoreBaseController;
import com.tianci.appstore.ui.data.SkyListSwitchData;
import com.tianci.appstore.ui.list.bootsetting.AutoStartDB;
import com.tianci.appstore.ui.list.bootsetting.LaunchOnBootSettinglistener;

import java.util.ArrayList;
import java.util.List;

public class BootUpAppManagerController extends AppStoreBaseController {

    private static BootUpAppManagerController instance = new BootUpAppManagerController();

    public static BootUpAppManagerController getInstance() {
        return instance;
    }

    private Cache<String, List<ComponentName>> cache = new Cache<String, List<ComponentName>>();
    private List<SkyListSwitchData> datas = new ArrayList<SkyListSwitchData>();
    private LaunchOnBootSettinglistener listener = null;

    private BootUpAppManagerController() {

    }

    public void init(LaunchOnBootSettinglistener l) {
        this.listener = l;
        runOnThread(new Runnable() {
            public void run() {
                PackageManager pm = mContext.getPackageManager();
                synchronized (datas) {
                    datas.clear();
                }
                cache.clear();
                List<ComponentName> names = Android.getComponentNames(mContext,
                        Intent.ACTION_BOOT_COMPLETED);

                List<ComponentName> _names = new ArrayList<ComponentName>();

                try {
                    LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
                    uri.addParams("filter", "autostart");
                    String result = LiteContentServiceConnecter.getService().call(uri.toString());
                    if (result != null) {
                        RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(result, RP_Installed_Apps.class);
                        if (rp.error_code == 0 && rp.resource != null
                                && rp.resource.total_count > 0) {
                            for (AppData item : rp.resource.resource_items) {
                                String pkg = item.info.pkgName;
                                if (pkg.equals("com.tianci.appstore"))
                                    continue;

                                for (ComponentName cn : names) {
                                    if (cn.getPackageName().equals(pkg)) {
                                        _names.add(cn);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                for (ComponentName name : _names) {
                    ApplicationInfo info = null;
                    try {
                        info = pm.getApplicationInfo(name.getPackageName(), 0);
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    List<ComponentName> __names = cache.get(name.getPackageName());
                    if (__names == null) {
                        __names = new ArrayList<ComponentName>();
                        cache.add(name.getPackageName(), __names);
                        SkyListSwitchData data = new SkyListSwitchData();
                        if (info != null)
                            data.setTitle(info.loadLabel(pm).toString());
                        data.setPkgName(name.getPackageName());
                        data.setObj(name);
                        int val = Android.getComponentEnabledSetting(mContext, name);
                        if (val == PackageManager.COMPONENT_ENABLED_STATE_DISABLED)
                            data.setSwitchOn(false);
                        else
                            data.setSwitchOn(true);
                        synchronized (datas) {
                            datas.add(data);
                        }
                    }
                    __names.add(name);
                }
                listener.onLaunchAppListLoaded(datas);

//                try {
//                    LiteURI uri = LiteURI.create("apps://com.coocaa.app/installed_apps");
//                    uri.addParams("filter", "autostart");
//                    String result = LiteContentServiceConnecter.getService().call(uri.toString());
//                    if (result != null) {
//                        RP_Installed_Apps rp = RP_Installed_Apps.parseJObject(result, RP_Installed_Apps.class);
//                        if (rp.error_code == 0 && rp.resource != null
//                                && rp.resource.total_count > 0) {
//                            for (AppData item : rp.resource.resource_items) {
//                                String pkg = item.info.pkgName;
//                                if (pkg.equals("com.tianci.appstore"))
//                                    continue;
//                                String activity = item.info.mainActivity;
//                                ComponentName cn = new ComponentName(pkg, activity);
//
//                                ApplicationInfo info = null;
//                                try {
//                                    info = pm.getApplicationInfo(cn.getPackageName(), 0);
//                                } catch (NameNotFoundException e) {
//                                    e.printStackTrace();
//                                }
//                                List<ComponentName> _names = cache.get(cn.getPackageName());
//                                if (_names == null) {
//                                    _names = new ArrayList<ComponentName>();
//                                    cache.add(cn.getPackageName(), _names);
//                                    SkyListSwitchData data = new SkyListSwitchData();
//                                    if (info != null)
//                                        data.setTitle(info.loadLabel(pm).toString());
//                                    data.setPkgName(cn.getPackageName());
//                                    data.setObj(cn);
//                                    int val = Android.getComponentEnabledSetting(mContext, cn);
//                                    if (val == PackageManager.COMPONENT_ENABLED_STATE_DISABLED)
//                                        data.setSwitchOn(false);
//                                    else
//                                        data.setSwitchOn(true);
//                                    synchronized (datas) {
//                                        datas.add(data);
//                                    }
//                                }
//                                _names.add(cn);
//                            }
//                        }
//                    }
//
//                    listener.onLaunchAppListLoaded(datas);
//                } catch (RemoteException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
            }
        });
    }

    public synchronized boolean setOneEnable(SkyListSwitchData data, boolean v) {
        boolean ret = false;
        List<ComponentName> names = cache.get(data.getPkgName());
        if (names != null) {
            for (ComponentName name : names) {
                Android.setComponentEnabledSetting(mContext, name,
                        v == true ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
                if (v == (Android.getComponentEnabledSetting(mContext,
                        (ComponentName) data.getObj()) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED))
                    ret = true;
                else
                    ret = false;
            }

            try {
                AutoStartDB ad = new AutoStartDB();
                List<LiteDBSupport> list = ad.select(null,null,null," pkg = ? ",data.getPkgName());
                if(list != null && list.size() > 0)
                {
                    ad.pkg = data.getPkgName();
                    ad.isEnable = v;
                    ad.update(" pkg = ? ",data.getPkgName());
                }else{
                    ad.pkg = data.getPkgName();
                    ad.isEnable = v;
                    ad.insert();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (ret)
                data.setSwitchOn(v);
            listener.onAppLaunchStatusChanged(data);
        }
        return ret;
    }

    public synchronized void setAllEnable(boolean v) {
        synchronized (datas) {
            for (SkyListSwitchData data : datas)
                setOneEnable(data, v);
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        listener = new LaunchOnBootSettinglistener(){
            @Override
            public void onLaunchAppListLoaded(List<SkyListSwitchData> dataList) {

            }

            @Override
            public void onAppLaunchStatusChanged(SkyListSwitchData data) {

            }
        };
    }

}
